package cur.nature.framework.core.util;

import lombok.Data;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.UUID;

/**
 * ID生成器工具类
 * 
 * @author ruoyi
 */
@Data
public class IdUtil {

    private Long workId;

    private static IdUtil workIdUtil;

    public IdUtil(final Long workId) {
        this.workId = workId;
    }

    public static void setWorkId(final IdUtil worker) {
        IdUtil.workIdUtil = worker;
    }

    public static IdUtil getIdUtil() {
        if (workIdUtil == null) {
            workIdUtil = new IdUtil(getWorkId());
        }
        return workIdUtil;
    }

    // 对外提供 uuid, 字符型
    public static String GUID(){
        String uuid = String.valueOf(java.util.UUID.randomUUID());
        uuid = uuid.replaceAll("-", "A");
        return uuid;
    }

    // 对外提供uuid , 数据型
    public static String generate(){
        return getIdUtil().random();
    }

    public String random(){
        return workId+""+System.nanoTime()+RandomUtils.nextLong(10,99);
    }

    private static Long getWorkId(){
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for(int b : ints){
                sums += b;
            }
            return (long)(sums % 256);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0,255);
        }
    }



    public static void main(String[] args) {

//        System.out.println(GUID());
//        System.out.println(System.currentTimeMillis());
        final String workId = getWorkId().toString();
        System.out.println(workId);
        for (int i = 0; i < 10; i++) {
            System.out.println(workId+System.nanoTime()+RandomUtils.nextLong(0,9));
        }
//        System.out.println(SnowflakeIdUtil.generateId());
    }

}
